package com.loe.test

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase

object NetCacheDb
{
    private var db: SQLiteDatabase? = null

    private const val name = "cache"

    fun init(context: Context)
    {
        if (db == null)
        {
            db = SQLiteDatabase.openOrCreateDatabase("${context.filesDir}/netCache.db", null)

            try
            {
                go(
                    """
                    CREATE TABLE $name ( 
                        url      VARCHAR(256) PRIMARY KEY      NOT NULL,
                        time    INTEGER(13),
                        data    VARCHAR
                    );
                    """.trimIndent()
                )
            } catch (e: Exception)
            {
            }
        }
    }

    fun put(url: String, data: String): NetCacheDb
    {
        val values = ContentValues()
        values.put("url", url)
        values.put("time", System.currentTimeMillis())
        values.put("data", data)
        db?.replace(name, null, values)
        return this
    }

    fun get(url: String): String?
    {
        var cursor: Cursor? = null
        try
        {
            cursor = db?.rawQuery("select data from $name where url='$url'", null)
            cursor?.let()
            {
                val s = cursor.getString(0)
                if (cursor.moveToNext())
                {
                    return cursor.getString(0)
                }
                cursor.close()
            }
        } catch (e: Exception)
        {
            if (cursor != null && !cursor.isClosed)
            {
                cursor.close()
            }
        }
        return null
    }

    fun got(url: String): String
    {
        return get(url) ?: ""
    }

    /**
     * 清除元素
     */
    fun clear()
    {
        db?.execSQL("delete from $name")
    }

//    var limitDuration = 7 * 24 * 60 * 60000
    var limitDuration = 60000

    /**
     * 清除过期元素
     */
    fun clearOld()
    {
        db?.execSQL("delete from $name where time<${System.currentTimeMillis() - limitDuration}")
    }

    fun go(sql: String)
    {
        db?.execSQL(sql)
    }

    /**
     * 开启事物
     */
    fun goTransaction(callBack: () -> Unit): Boolean
    {
        //开启事务
        db?.beginTransaction()
        try
        {
            callBack()
            //设置事务标志为成功，当结束事务时就会提交事务
            db?.setTransactionSuccessful()
        } catch (e: Exception)
        {
            return false
        } finally
        {
            //结束事务
            db?.endTransaction()
        }
        return true
    }
}